package com.wechat.controller;

import com.wechat.annotation.GlobalInterceptor;
import com.wechat.entity.config.AppConfig;
import com.wechat.entity.constants.Constants;
import com.wechat.entity.enums.AppUpdateFileTypeEnum;
import com.wechat.entity.enums.AppUpdateSatusEnum;
import com.wechat.entity.po.AppUpdate;
import com.wechat.entity.vo.AppUpdateVO;
import com.wechat.entity.vo.ResponseVO;
import com.wechat.service.AppUpdateService;
import com.wechat.utils.StringTools;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;

/*
 * 检测更新
 */
@RestController("checkUpdateController")
@RequestMapping("/update")
public class CheckUpdateController extends ABaseController {

    @Resource
    private AppUpdateService appUpdateService;
    @Resource
    private AppConfig appConfig;

    /**
     * 检测版本
     *
     * @param appVersion---传入当前用户的版本号
     * @param uid------用户id
     * @return
     */
    @RequestMapping("/checkVersion")
    @GlobalInterceptor
    public ResponseVO checkVersion(String appVersion, String uid) {
        if (StringTools.isEmpty(appVersion)) {
            return getSuccessResponseVO(null);
        }
        AppUpdate dbAppUpdate = appUpdateService.getLatestUpdate(appVersion, uid);
        if (dbAppUpdate == null) {//已是最新版，无需更新
            return getSuccessResponseVO(null);
        }
        AppUpdateVO appUpdateVO = new AppUpdateVO();
        BeanUtils.copyProperties(dbAppUpdate, appUpdateVO);
        //如果发布版是外链，则不返回文件大小
        if(dbAppUpdate.getFileType().equals(AppUpdateFileTypeEnum.OUTER_LINK.getType())){
            appUpdateVO.setSize(0L);
        }else{//以本地文件发布，则返回文件大小
            File file = new File(appConfig.getProjectFolder()
                    + Constants.APP_UPDATE_FOLDER
                    + dbAppUpdate.getId()
                    + Constants.APP_EXE_SUFFIX);//文件名
            appUpdateVO.setSize(file.length());//文件大小
        }
        appUpdateVO.setUpdateList(Arrays.asList(dbAppUpdate.getUpdateDescArray()));//将sting数组转换为list<String>
        String fileName = Constants.APP_NAME + dbAppUpdate.getVersion() + Constants.APP_EXE_SUFFIX;
        appUpdateVO.setFileName(fileName);

        return getSuccessResponseVO(appUpdateVO);
    }


}
